/*
Search a 2D Matrix 

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
Given target = 3, return true.
*/
#include <iostream>
#include <vector>
#include  <algorithm>

using namespace std;

class Solution {
public:
	int lowBounder(vector<int> &vec, int target)
	{
		int first = 0;
		int size = vec.size()-1;
		int middle;
		int half;

		while (size>0)
		{
			half = size >> 1;
			

			middle = first + half;

			if (vec[middle]<target)
			{
				first = middle + 1;
				
				size = size - half - 1;
			}
			else
			{
				size = half;
			}

		}
		return first;
	}
	
    bool searchMatrix(vector<vector<int> >& matrix, int target) {
        int rowSize = matrix.size();
		int colSize = matrix[0].size();
		//cout<<"row : "<<rowSize<<endl;
		vector<int> vecTemp(rowSize,0);
		for (int i = 0; i < rowSize; i++)
		{
			vecTemp[i] = matrix[i][0];
		}

		int row = lowBounder(vecTemp, target);
		int cloumn = 0;
		cout<<"row : "<<row<<endl;
		
		if (matrix[row][0] == target)
		{
			return true;
		}
		else if (row == 0|| ((row == rowSize-1)&&(matrix[row][0]< target)))
		{
			vecTemp = matrix[row];
			cloumn = lowBounder(vecTemp, target);
			if (matrix[row][cloumn] == target)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			vecTemp = matrix[row-1];
			cloumn = lowBounder(vecTemp, target);
			if (matrix[row-1][cloumn] == target)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

	

		
    }
};
int main()
{
	cout<<"Set Matrix Zeros"<<endl;
	int a1[] = {1,3,5,7};
	int a2[] = {10,11,16,20};
	int a3[] = {23,30,34,50};
	vector<vector<int> > matrix;
	vector<int> element1(a1, a1 + sizeof(a1)/sizeof(int));
	vector<int> element2(a2, a2 + sizeof(a2)/sizeof(int));
	vector<int> element3(a3, a3 + sizeof(a3)/sizeof(int));
	
	matrix.push_back(element1);
	matrix.push_back(element2);
	matrix.push_back(element3);
	
	cout<<"size: " << matrix.size()<<endl;
	Solution s;
	int target = 11;
	
	if(s.searchMatrix(matrix,target))
		cout<<target<<" is in the matrix"<<endl;
	else
		cout<<"No "<< target<<" is in the matrix"<<endl;
	
	
	return 0;
}